package com.framework.util;

import com.sun.media.sound.SoftTuning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.net.www.content.text.Generic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Properties;

/**
 * Created by
 *
 * @author dw
 * @date 2018/01/21
 */
public class PropsUtil {
    private static final Logger logger = LoggerFactory.getLogger(PropsUtil.class);

    public static Properties loadProps(String filename) {
        Properties prop = null;
        InputStream in = null;

        try {
            in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
            if (null == in) {
                throw new FileNotFoundException(filename + " not found");
            }
            prop = new Properties();
            prop.load(in);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return prop;
    }

    public static <T> T getValueBykey(Properties p, String key, Class<T> t) {

        logger.debug("通过泛型读取配置文件属性,key:" + key + "  " + t.toString());
        Object reback = null;
        if (null != p) {
            reback = p.get(key);
        }

        if (t.toString().equals(String.class.toString())) {
            return (T) String.valueOf(reback);
        }
        if (t.toString().equals(Integer.class.toString())) {
            String temp = String.valueOf(reback);
            return (T) (Integer.valueOf(temp));
        }
        if (t.toString().equals(Double.class.toString())) {
            String temp = String.valueOf(reback);
            return (T) (Double.valueOf(temp));
        }
        if (t.toString().equals(Boolean.class.toString())) {
            String temp = String.valueOf(reback);
            return (T) (Boolean.valueOf(temp));
        }
        return null;
    }
}
